const { User } = require('../../../model/user')
const { setToken } = require('../../../token/token')
const bcrypt = require('bcrypt')
module.exports = async(req, res) => {
  const { email, password, captcha, captchaReg } = req.body
  console.log(req.body);
  if (captcha !== captchaReg) return res.send({ meta: { status: 400, msg: '验证码错误' } })
  if (email.trim().length == 0 || password.trim().length == 0) return res.send({ meta: { status: 400, msg: '邮箱地址或者密码错误' } })
  const user = await User.findOne({ email })
  if (user) {
    const isValid = await bcrypt.compare(password, user.password)
    if (isValid) {
      const token = await setToken(user.nickName, user._id)
      const { _id, email, nickName, introduction, registerTime } = user
      return res.send({ data: { _id, email, nickName, introduction, registerTime, token }, meta: { status: 200, msg: '登录成功' } })
    }
  }
  res.send({ meta: { status: 400, msg: '邮箱地址或者密码错误' } })
}
